package com.gongpingjialoan.activity.car;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.gongpingjialoan.R;
import com.gongpingjialoan.activity.main.BaseActivity;
import com.gongpingjialoan.adapter.CarSourceListAdapter;
import com.gongpingjialoan.api.API;
import com.gongpingjialoan.bean.CarSource;
import com.gongpingjialoan.bean.DealerCat;
import com.gongpingjialoan.network.NetDataJson;
import com.gongpingjialoan.view.DelearTabView;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/5/16.
 */
public class DelearActivity extends BaseActivity implements AbsListView.OnItemClickListener, NetDataJson.OnNetDataJsonListener,
        PullToRefreshBase.OnRefreshListener<ListView>, PullToRefreshBase.OnLastItemVisibleListener {


    private PullToRefreshListView pullToRefreshListView;

    private ListView listView;

    private CarSourceListAdapter carSourceAdapter;

    private int pageIndex;

    private boolean isLoadingMore;

    private boolean hasMore;

    private List<CarSource> carSourceDataList;

    private NetDataJson netWork;

    private boolean isRefresh = true;

    private View suggestHeadView;
    // request network need item:

    private String cityName, provice;

    private View footView;
    private ImageView noinfo;

    DelearTabView tabV;

    String dealer_id;
    String domain;

    String tel;

    String sort = "", year = "", price = "", brand = "", model = "";

    int sortindex;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        isSendData = true;
        isScrollPage = true;
        action = "detail_sameDealer";
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_delear);
        domain = getIntent().getStringExtra("domain");
        setTitle(domain);
        suggestHeadView = LayoutInflater.from(this).inflate(R.layout.suggest_head, null);
        suggestHeadView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            }
        });
        footView = LayoutInflater.from(this).inflate(R.layout.listview_footview, null);
        initView();
    }

    private void initView() {
        dealer_id = getIntent().getStringExtra("dealer_id");
        cityName = getIntent().getStringExtra("city");
        provice = getIntent().getStringExtra("province");
        noinfo = (ImageView) findViewById(R.id.no_info);
        netWork = new NetDataJson(this);
        pullToRefreshListView = (PullToRefreshListView) findViewById(R.id.listview);
        pullToRefreshListView.setScrollingWhileRefreshingEnabled(false);
        pullToRefreshListView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
        pullToRefreshListView.setOnRefreshListener(this);

        pullToRefreshListView.setOnLastItemVisibleListener(this);

        carSourceDataList = new ArrayList<CarSource>();

        pageIndex = 1;
        isLoadingMore = true;
        hasMore = true;

        carSourceAdapter = new CarSourceListAdapter(this);
        listView = pullToRefreshListView.getRefreshableView();
        listView.addHeaderView(suggestHeadView);
        listView.addFooterView(footView);
        listView.setAdapter(carSourceAdapter);
        listView.setOnItemClickListener(this);
        listView.removeHeaderView(suggestHeadView);
        listView.removeFooterView(footView);
        carSourceAdapter.notifyDataSetChanged();

        tabV = (DelearTabView) findViewById(R.id.tab);
        tabV.setOnTabSelectListener(new DelearTabView.OnTabSelectListener() {
            @Override
            public void sort(DealerCat cat) {
                if ("year".equals(cat.getKey())) {
                    year = cat.getValue();
                } else if ("price".equals(cat.getKey())) {
                    price = cat.getValue();
                } else if ("sort".equals(cat.getKey())) {
                    sort = cat.getValue();
                }
                pullToRefreshListView.setRefreshing();
            }

            @Override
            public void brand(String brandName, String brandSlug, String modelname, String modelsulg) {
                brand = brandSlug;
                model = modelsulg;
                pullToRefreshListView.setRefreshing();
            }
        });
        listView.postDelayed(new Runnable() {
            @Override
            public void run() {
                pullToRefreshListView.setRefreshing();
            }
        }, 200);
        getDealerInfo();

    }


    private void getDealerInfo() {
        NetDataJson netWork = new NetDataJson(new NetDataJson.OnNetDataJsonListener() {
            @Override
            public void onDataJsonError(String errorMessage) {
                Toast.makeText(DelearActivity.this, errorMessage, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onDataJsonUpdate(JSONObject json) {

                try {
                    tel = json.getString("phone");
                    findViewById(R.id.tel).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + tel));
                            startActivity(intent);
                        }
                    });
                    TextView carCountT = (TextView) findViewById(R.id.car_count);
                    carCountT.setText(json.getString("all_sell_car_num"));

                    TextView addressT = (TextView) findViewById(R.id.address);
                    addressT.setText(json.getString("address"));

                    LinearLayout stars = (LinearLayout) findViewById(R.id.star);
                    double rate = json.getDouble("rate");
                    for (int j = 0; j < Math.floor(rate); j++) {
                        ImageView imageView = (ImageView) stars.getChildAt(j);
                        imageView.setImageResource(R.drawable.star);
                    }
                    if (rate > Math.floor(rate)) {
                        ImageView imageView = (ImageView) stars.getChildAt((int) Math.floor(rate));
                        imageView.setImageResource(R.drawable.ban_star);
                    }

                    boolean is_certify = json.getBoolean("is_certify");
                    ImageView renzhengI = (ImageView) findViewById(R.id.renzheng);
                    renzhengI.setImageResource(is_certify ? R.drawable.dealer_renzheng : R.drawable.delear_weirenzheng);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                try {
                    JSONArray jsa = json.getJSONArray("sell_car_num_dict");
                    tabV.setData(jsa, json.getString("all_sell_car_num"));
                } catch (JSONException e) {
                }


            }
        });
        netWork.setUrl(API.delear_info);
        netWork.addParam("dealer_id", dealer_id);
        netWork.addParam("city", cityName);
        netWork.addParam("province", provice);
        netWork.request("get");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (netWork != null) {
            netWork.cancelTask();
            netWork = null;
        }
    }

    // 加载更多
    private void LoadMoreData() {

        if (!hasMore) {
            Toast.makeText(this, "没有更多了", Toast.LENGTH_SHORT).show();
            return;
        }

        if (!isLoadingMore && hasMore && carSourceDataList.size() > 0) {
            listView.addFooterView(footView);
            listView.setSelection(listView.getBottom());
            isRefresh = false;
            isLoadingMore = true;
            pageIndex++;
            updateData();
        }
    }


    private void updateData() {
        netWork.clearMap();
        netWork.setUrl(API.carListSearch);
        netWork.addParam("page", pageIndex);
        netWork.addParam("dealer_id", dealer_id);
        netWork.addParam("province", getIntent().getStringExtra("province"));
        netWork.addParam("sort", sort);
        netWork.addParam("brand", brand);
        netWork.addParam("model", model);
        netWork.addParam("year", year);
        netWork.addParam("price", price);
        netWork.request("get");
    }


    // 重新获取数据
    private void onUpdateData() {
        noinfo.setVisibility(View.GONE);
        isRefresh = true;
        pageIndex = 1;
        hasMore = true;
        updateData();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (position == 0) return;
        Intent intent = new Intent();
        intent.setClass(this, CarBuyDetailActivity.class);
        CarSource carSource = (CarSource) view.getTag(R.id.tag_second);
        intent.putExtra("typevalue", String.valueOf(carSource.mId));
        intent.putExtra("type", "domain");
        intent.putExtra("from", from);
        startActivity(intent);
    }

    @Override
    public void onLastItemVisible() {
        LoadMoreData();
    }

    @Override
    public void onDataJsonError(String errorMessage) {
        Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT).show();
        if (isLoadingMore && !isRefresh) {
            listView.removeFooterView(footView);
        }
        isLoadingMore = false;
        pullToRefreshListView.onRefreshComplete();
    }

    @Override
    public void onDataJsonUpdate(JSONObject json) {
        JSONArray jsonArray = null;
        if (isLoadingMore && !isRefresh) {
            listView.removeFooterView(footView);
        }
        if (isRefresh) {
            carSourceDataList.clear();
            listView.removeHeaderView(suggestHeadView);
            carSourceAdapter.notifyDataSetChanged();
        }
        try {
            jsonArray = json.getJSONArray("car_list");
            if (0 == jsonArray.length()) {
                JSONArray suggestJsonArray = json.getJSONArray("suggest_list");
                if (suggestJsonArray.length() == 0) {
                    Toast.makeText(this, "未找到相应数据", Toast.LENGTH_SHORT).show();
                    noinfo.setVisibility(View.VISIBLE);
                    isLoadingMore = false;

                    pullToRefreshListView.onRefreshComplete();

                } else {
                    //建议车源
                    isLoadingMore = false;
                    hasMore = false;
                    pullToRefreshListView.onRefreshComplete();
                    listView.addHeaderView(suggestHeadView);
                    getDataFromJsonArray(suggestJsonArray);
                    updateListView();
                }
                return;
            }
            getDataFromJsonArray(jsonArray);

            int page_num = json.getInt("page_num");
            if (page_num == pageIndex) {
                hasMore = false;
            }

        } catch (JSONException e) {
            Toast.makeText(this, "未找到相应数据", Toast.LENGTH_SHORT).show();
            isLoadingMore = false;
            pullToRefreshListView.onRefreshComplete();
            return;
        }

        updateListView();
    }


    private void updateListView() {
        if (carSourceDataList.size() != 0) {
            carSourceAdapter.setData(carSourceDataList);
            pullToRefreshListView.onRefreshComplete();
            isLoadingMore = false;
        } else {
            noinfo.setVisibility(View.VISIBLE);
        }
    }


    //判断是否多个城市
    private boolean isMoreCity() {
        if (!TextUtils.isEmpty(provice)) {
            return true;
        }
        String citys[] = cityName.split(",");
        if (citys.length <= 1) {
            return false;
        } else {
            return true;
        }
    }

    private void getDataFromJsonArray(JSONArray jsonArray) throws JSONException {
        // Log.e("getDataFromJsonArray", "getDataFromJsonArray");
        for (int i = 0; i < jsonArray.length(); i++) {
            CarSource carSrc = new CarSource();
            JSONObject object = jsonArray.getJSONObject(i);
            carSrc.mCity = cityName;
            if (isMoreCity() || listView.getHeaderViewsCount() > 1) {
                carSrc.newCity = object.getString("city");
            }
            carSrc.mTitle = object.getString("title");
            carSrc.mYear = object.getString("year");
            carSrc.mMile = object.getString("mile").equals("None") ? "" : object.getString("mile");
            carSrc.mPrice = Double.valueOf(object.getString("price"));
            carSrc.mId = object.getInt("id");
            carSrc.mThumbnail = object.getString("thumbnail");
            carSrc.mTime = object.getString("time");
            carSrc.hasmodel = object.getString("has_model_detail");
            carSrc.pub_timestamp = object.getString("pub_timestamp");
            // carSrc.mRecommend = object.getString("recommend");
            carSrc.isactive = object.getBoolean("seller_active");
            carSrc.mSourceType = object.getString("source_type");
            carSrc.mGpjIndex = object.getDouble("gpj_index");
            carSrc.mQsTags = object.getString("qs_tags");
            carSrc.mSource = object.getString("domain");
            carSrc.is_certify = object.getBoolean("is_certify");
            carSrc.pubTime = object.getString("pub_time");
            carSrc.brand_zh = object.getString("brand_slug_zh");
            carSrc.model_zh = object.getString("model_slug_zh");
            carSrc.model_detail_zh = object.getString("model_detail_slug_zh");
            carSrc.cs_clean = object.getBoolean("cs_clean");
            carSrc.origin_price = object.getString("origin_price");
            carSrc.lowest_price = object.getString("lowest_price");
            carSrc.last_price = object.getString("last_price");
            carSrc.setBrand(object.getString("brand_slug"));
            carSrc.setModel(object.getString("model_slug"));

            carSrc.mUrl = carSrc.mThumbnail;
            carSourceDataList.add(carSrc);
        }
    }


    boolean isFristLoading = true;

    @Override
    public void onRefresh(PullToRefreshBase<ListView> refreshView) {
        if (!isFristLoading) {
            String label =
                    "更新时间:" + DateUtils.formatDateTime(this, System.currentTimeMillis(), DateUtils.FORMAT_SHOW_TIME
                            | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);
            refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
        }
        isFristLoading = false;
        onUpdateData();
    }
}
